package com.x.service.transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.x.dao.RoleDAO;
import com.x.dao.UserDAO;
import com.x.model.Role;
import com.x.model.User;

@Component("userService")
public class UserService {

	@Autowired
	private UserDAO userDAO;
	@Autowired
	private RoleDAO roleDAO;

	public void update(User user) {
		userDAO.saveUser(user);
	}

	public Map<String, Object> list(int startIndex, int length,
			String searchValue, List<String> wherePart, List<String[]> odrerPart) {
		return userDAO.list(startIndex, length, searchValue, wherePart,
				odrerPart);
	}

	public Map<String, Object> load(String id) {
		User user = userDAO.load(id);
		Map<String, Object> result = new HashMap<>();
		result.put("id", user.getId());
		result.put("username", user.getUsername());
		result.put("nickname", user.getNickname());
		if (user.getRoles().size() > 0) {
			result.put("roleId", user.getRoles().get(0).getId());
			result.put("roleName", user.getRoles().get(0).getRole());
		}
		return result;
	}

	public void create(String username, String nickname, String roleId) {
		User user = new User();
		List<Role> roles = new ArrayList<Role>();
		Role role = roleDAO.getById(roleId);
		roles.add(role);
		user.setUsername(username);
		user.setPassword("202cb962ac59075b964b07152d234b70");
		user.setNickname(nickname);
		user.setCreatetime(new Timestamp(System.currentTimeMillis()));
		user.setRoles(roles);
		user.setEnabled(true);
		userDAO.saveUser(user);
	}

	public void update(String id, String username, String nickname,
			String roleId) {
		User user = userDAO.load(id);
		List<Role> roles = new ArrayList<Role>();
		Role role = roleDAO.getById(roleId);
		roles.add(role);
		user.setUsername(username);
		user.setNickname(nickname);
		user.setRoles(roles);
		user.setEnabled(true);
		userDAO.saveUser(user);
	}

	public void delete(String id) {
		userDAO.delete(id);

	}

	public String getRoleByName(String username) {
		return userDAO.getRoleByName(username);
	}

	public boolean exsit(String username) {
		User user = userDAO.getUserByName(username);
		if (null == user) {
			return false;
		}
		return true;
	}

	public User getUserByName(String username) {
		return userDAO.getUserByName(username);
	}
}
